<template>
  <div class="filter-option"
       style="margin-right:10px;margin-bottom:10px;"
       :class="{ 
      'active': isActive,
      'has-children': hasChildren
    }"
       @click.stop="handleClick">
    <!-- 选项名称 -->
    <span class="option-name">{{ levelData.standardName }}</span>
  </div>
</template>

<script setup lang="ts">
  import { defineProps, computed } from "vue";

  // 定义层级数据接口
  export interface LevelData {
    id: string | number;
    standardName: string;
    children?: LevelData[];
  }

  // 定义组件属性
  const props = defineProps<{
    levelData: LevelData;
    depth: number; // 当前层级深度（0:第一层级, 1:第二层级...）
    selectedIds: (string | number)[];
    expandedIds: (string | number)[];
  }>();

  // 定义组件事件
  const emit = defineEmits<{
    (e: "toggle-expand", id: string | number): void;
    (
      e: "toggle-select",
      payload: { ids: (string | number)[]; isSelect: boolean }
    ): void;
  }>();

  // 计算属性：是否有子级
  const hasChildren = computed(() => {
    return (
      Array.isArray(props.levelData.children) &&
      props.levelData.children.length > 0
    );
  });

  // 计算属性：是否被选中
  const isActive = computed(() => {
    return props.selectedIds.includes(props.levelData.id);
  });

  // 计算属性：子级ID列表
  const childIds = computed<(string | number)[]>(() => {
    if (!hasChildren.value) return [];
    return props.levelData.children!.map(child => child.id);
  });

  // 计算属性：是否全选子级
  const isSelectAllChildren = computed(() => {
    if (!hasChildren.value) return false;
    return childIds.value.every(id => props.selectedIds.includes(id));
  });

  // 处理点击事件
  const handleClick = () => {
    // 触发选中状态变更
    if (hasChildren.value) {
      // 有子级：选中/取消选中所有子级
      emit("toggle-select", {
        ids: childIds.value,
        isSelect: !isSelectAllChildren.value,
      });
    } else {
      // 无子级：切换自身选中状态
      emit("toggle-select", {
        ids: [props.levelData.id],
        isSelect: !isActive.value,
      });
    }

    // 如果有子级，同时触发展开/折叠
    if (hasChildren.value) {
      emit("toggle-expand", props.levelData.id);
    }
  };
</script>

<style scoped>
  .filter-option {
    display: inline-flex;
    align-items: center;
    padding: 6px 12px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    transition: all 0.2s ease;
    background-color: #f9fafb;
    color: #374151;
    border: 1px solid transparent;
  }

  .filter-option:hover {
    background-color: #f3f4f6;
    border-color: #e5e7eb;
  }

  .filter-option.active {
    background-color: #eff6ff;
    color: #1d4ed8;
    border-color: #bfdbfe;
    font-weight: 500;
  }

  /* .filter-option.has-children {
                position: relative;
              } */

  .expand-icon {
    margin-right: 6px;
    font-size: 12px;
    color: #6b7280;
  }
</style>
